package com.bqtv.sport.app

import android.app.Application
import android.content.Context
import androidx.core.content.ContextCompat
import com.hjq.base.http.cookie.CookieJarImpl
import com.hjq.base.http.cookie.PersistentCookieStore
import com.bqtv.sport.commen.utils.glide.GlideApp
import com.hjq.bar.TitleBar
import com.hjq.http.EasyConfig
import com.hjq.http.config.IRequestInterceptor
import com.hjq.http.config.IRequestServer
import com.hjq.http.model.HttpHeaders
import com.hjq.http.model.HttpParams
import com.hjq.http.request.HttpRequest
import com.hjq.http.ssl.HttpSslFactory
import com.hjq.toast.Toaster
import com.bqtv.sport.BuildConfig
import com.bqtv.sport.R
import com.bqtv.sport.commen.utils.ActivityManager
import com.hjq.base.app.LoginInfoUtils
import com.bqtv.sport.commen.utils.MMKVUtils
import com.bqtv.sport.commen.utils.TitleBarStyle
import com.bqtv.sport.commen.utils.ToastStyle
import com.bqtv.sport.commen.utils.crash.CrashHandler
import com.bqtv.sport.commen.widget.SmartBallPulseFooter
import com.bqtv.sport.ui.main.LoginActivity
import com.hjq.base.http.ReleaseServer
import com.hjq.base.http.RequestHandler
import com.scwang.smart.refresh.header.MaterialHeader
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.tencent.bugly.crashreport.CrashReport
import com.tencent.mmkv.MMKV
import com.tencent.qcloud.tuicore.TUILogin
import com.tencent.qcloud.tuicore.interfaces.TUILoginListener
import me.jessyan.autosize.AutoSizeConfig
import okhttp3.OkHttpClient
import java.util.concurrent.TimeUnit


class MyApp : Application() {
    override fun onCreate() {
        super.onCreate()
        sInstance = this
        initSdk(this)
    }

    override fun onLowMemory() {
        super.onLowMemory()
        // 清理所有图片内存缓存
        GlideApp.get(this).onLowMemory()
    }

    override fun onTrimMemory(level: Int) {
        super.onTrimMemory(level)
        // 根据手机内存剩余情况清理图片内存缓存
        GlideApp.get(this).onTrimMemory(level)
    }

    /**
     * 初始化一些第三方框架
     */
    open fun initSdk(application: Application) {
        // 设置标题栏初始化器
        TitleBar.setDefaultStyle(TitleBarStyle())


        // 设置全局的 Header 构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator { context: Context, _: RefreshLayout ->
            MaterialHeader(context).setColorSchemeColors(
                ContextCompat.getColor(
                    context,
                    R.color.colorPrimary
                )
            )
        }
        // 设置全局的 Footer 构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator { context, layout -> //指定为经典Footer，默认是 BallPulseFooter
            SmartBallPulseFooter(context)
        }
//            // 设置全局初始化器
        SmartRefreshLayout.setDefaultRefreshInitializer { context: Context, layout: RefreshLayout ->
            layout
                // 内容不满一页时是否可以上拉加载更多
                .setEnableLoadMoreWhenContentNotFull(false)
        }

        // 初始化吐司
        Toaster.init(application, ToastStyle())
        // 设置调试模式
        Toaster.setDebugMode(AppConfig.isDebug())
        // 设置 Toast 拦截器
//            ToastUtils.setInterceptor(ToastLogInterceptor())


        // 本地异常捕捉
        CrashHandler.register(application)

        // Bugly 异常捕捉
        CrashReport.initCrashReport(application, AppConfig.getBuglyId(), AppConfig.isDebug())

        // Activity 栈管理初始化
        ActivityManager.getInstance().init(application)

        // MMKV 初始化
        MMKV.initialize(application)
        initEasyHttp()

        initTXIM()

        AutoSizeConfig.getInstance().apply {
            designWidthInDp = 375
            designHeightInDp = 812
            isExcludeFontScale = true
            isCustomFragment = true
        }
    }

    private fun initEasyHttp() {
        val builder: OkHttpClient.Builder = OkHttpClient.Builder()
        //超时时间设置
        builder.readTimeout(10000, TimeUnit.MILLISECONDS) //全局的读取超时时间
        builder.writeTimeout(10000, TimeUnit.MILLISECONDS) //全局的写入超时时间
        builder.connectTimeout(10000, TimeUnit.MILLISECONDS) //全局的连接超时时间
        builder.cookieJar(CookieJarImpl(PersistentCookieStore(this))) //cookie持久化，如果cookie不过期，则一直有效
//            //方法一：信任所有证书,不安全有风险
        val sslConfig = HttpSslFactory.generateSslConfig()
        builder.sslSocketFactory(sslConfig.sslSocketFactory, sslConfig.trustManager)
        builder.hostnameVerifier(HttpSslFactory.generateUnSafeHostnameVerifier())

        // 网络请求框架初始化
        val server: IRequestServer
        if (BuildConfig.DEBUG) {
            server = ReleaseServer()
        } else {
            server = ReleaseServer()
        }

        val okHttpClient = builder.build()

        val requestHandler=RequestHandler(this)
        requestHandler.setDealTokenException {
            // 进行内存优化，销毁所有界面
            ActivityManager.getInstance().finishAllActivities()
            LoginInfoUtils.resetUserInfo()
            sInstance?.let {
//                LoginActivity.start(it)
            }
        }

        EasyConfig.with(okHttpClient)
            // 是否打印日志
            .setLogEnabled(AppConfig.isLogEnable())
            // 设置服务器配置
            .setServer(server)
            // 设置请求处理策略
            .setHandler(requestHandler)
            .setInterceptor(object : IRequestInterceptor {
                override fun interceptArguments(
                    httpRequest: HttpRequest<*>,
                    params: HttpParams,
                    headers: HttpHeaders
                ) {
                    headers.put("timestamp", System.currentTimeMillis().toString())
                    headers.put("Accept", "application/json")
                }
            })
            //请求头
            .addHeader("Authorization", LoginInfoUtils.getToken())
            // 设置请求重试次数
            .setRetryCount(1)
            .into()
    }

    private fun initTXIM() {
        TUILogin.addLoginListener(object : TUILoginListener() {
            override fun onKickedOffline() {
                super.onKickedOffline()
                // 进行内存优化，销毁所有界面
                ActivityManager.getInstance().finishAllActivities()
                LoginInfoUtils.resetUserInfo()
                sInstance?.let {
                    LoginActivity.start(it)
                }
            }
        })
        //todo
//        TUIChatConfigs.getGeneralConfig().isMsgNeedReadReceipt = true;
    }

    companion object {

        var sInstance: Application? = null

        /**
         * 获得当前app运行的Application
         */
        fun getInstance(): MyApp? {
            if (sInstance == null) {
                throw NullPointerException("please inherit BaseApplication or call setApplication.")
            }
            return sInstance as MyApp?
        }
    }
}